package com.qmo.edu.http;

import android.util.Log;


import com.qmo.edu.constant.ApiUrl;
import com.qmo.edu.http.ApiService;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;



/**
 * Created by ${} on 2019/3/25/025.
 *
 * @author cyx
 */

public class RetrofitHelper {
    private static RetrofitHelper mRetrofitHelper;
    private String TAG = "RetrofitHelper";
    private Retrofit mRetrofit;

    private RetrofitHelper() {
        init();
    }

    private void init() {
        OkHttpClient client = new OkHttpClient.Builder()
                .readTimeout(10, TimeUnit.SECONDS)
                .connectTimeout(10, TimeUnit.SECONDS)
                .addInterceptor(mInterceptor)
                .build();

        mRetrofit = new Retrofit.Builder()
                .baseUrl(ApiUrl.BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .addConverterFactory(ScalarsConverterFactory.create())
                .client(client)
                .build();
    }

    public static RetrofitHelper instance() {
        if (mRetrofitHelper == null) {
            synchronized (RetrofitHelper.class) {
                mRetrofitHelper = new RetrofitHelper();
            }
        }
        return mRetrofitHelper;
    }


    private Interceptor mInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();

            long startTime = System.currentTimeMillis();
            Response response = chain.proceed(request);
            long endTime = System.currentTimeMillis();
            long duration = endTime - startTime;

            MediaType mediaType = response.body().contentType();
            String content = response.body().string();
            Log.e(TAG, "---------------- Request Start ---------------------");
            Log.e(TAG, "|" + request.toString() + request.headers().toString());
            Log.e(TAG, "|" + content);
            Log.e(TAG, "---------------- Request End --- " + duration + " 毫秒--------");
            return response.newBuilder()
                    .body(ResponseBody.create(mediaType, content))
                    .build();
        }
    };

    public com.qmo.edu.http.ApiService getApiService() {
        return mRetrofit.create(ApiService.class);
    }
}
